// pages/go-jianbao/jianbao.js
import {
  ajax,
  src,
  util
} from "../../utils/util.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    length:0,
    zw: '',
    headImg: [],
    showvoi: false,
    jb_id:'',
  },
  // 获取正文
  getzw: function (e) {
    console.log(e)
    this.setData({
      zw: e.detail.value
    })
  },
  // 显示弹框   照片或视频
  tcchangevori: function () {
    this.setData({
      showvoi: true
    })
  },
  // 取消弹框  照片或视频
  closetc: function () {
    this.setData({
      showvoi: false
    })
  },
  // 提交
  tijiao: function () {
    if (this.data.zw == '') {
      wx.showToast({
        title: "请输入正文",
        icon: 'none',
        duration: 3000,
      })
      return
    }
    if (this.data.headImg.length == 0) {
      wx.showToast({
        title: "请输入添加视频或图片",
        icon: 'none',
        duration: 3000,
      })
      return
    }


    wx.showLoading({
      title: '上传中',
    })

    ajax('/api/index/jianbao_add', {
      data: {
        uqid: wx.getStorageSync('uqid'),
        desc: this.data.zw
      },
      header: {
        'Accept': 'application/x-www-form-urlencoded', // 默认值
      },
      method: "post",
    }, res => {
      this.setData({
        jb_id: res.data.jb_id
      })

      this.uploadimg({
        url: src + '/api/index/jianbao_image_add', //这里是你图片上传的接口
        image: this.data.headImg //这里是选取的图片的地址数组        
      });

    })

  },
  // 返回上一页
  back: function () {
    wx.navigateBack({
      delta: 1
    })
  },
  // 上传多张
  uploadimg(data) {
    var that = this
    var uqid = that.data.uqid
    var i = data.i ? data.i : 0//当前上传的哪张图片

    var success = data.success ? data.success : 0 //上传成功的个数
    var fail = data.fail ? data.fail : 0 //上传失败的个数
    console.log(i)
    wx.uploadFile({
      url: data.url,
      filePath: data.image[i].url,
      name: 'image', //这里根据自己的实际情况改
      formData: {

        uqid: wx.getStorageSync('uqid'),
        jb_id: that.data.jb_id,

      }, //这里是上传图片时一起上传的数据
      header: { "Content-Type": "multipart/form-data" },
      success(resU) {
        success++;

        // console.log(resU)
        // if (JSON.parse(resU.data).error == 0) {
        //   wx.showToast({
        //     title: '上传成功,请到我的病历中查看！',
        //     icon: 'none',
        //     duration: 1000
        //   })
        // }
      },
      fail: (res) => {
        fail++; //图片上传失败，图片上传失败的变量+1
        console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
        console.log(i);
        i++; //这个图片执行完上传后，开始上传下一张            
        if (i == data.image.length) { //当图片传完时，停止调用   
          wx.hideLoading();
          console.log('执行完毕');
          console.log('成功：' + success + " 失败：" + fail)
          // return ('成功：' + success + " 失败：" + fail);

          wx.showToast({
            title: "上传成功",
            icon: 'none',
            duration: 3000,
            success: this.back
          })


        } else { //若图片还没有传完，则继续调用函数     
          wx.hideLoading();
          console.log(i);
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);
        }
      }
    })
  },
  // 选图片
  uploadimages: function () {
    this.closetc()

    var uqid = this.data.uqid;
    console.log(uqid)
    var that = this
    wx.showActionSheet({
      itemList: ['从相册选取', '拍照'],
      success(res) {
        console.log(res.tapIndex)
        var index = res.tapIndex;

        var headImg = that.data.headImg;
        if (index == 0) {

          let num = 9; //一次最大上传九张

          if (headImg.length > 0) {
            num = 9 - headImg.length;
          }

          wx.chooseImage({
            count: num,
            sizeType: ['original', 'compressed'],
            sourceType: ['album'],
            success(res) {
              console.log(res)
              // tempFilePath可以作为img标签的src属性显示图片
              const tempFilePaths = res.tempFilePaths;
              console.log(tempFilePaths)


              for (let i = 0; i < tempFilePaths.length; i++) {
                var obj = {}
                obj.style = 1
                obj.url = tempFilePaths[i]
                headImg.push(obj)
              }
              that.setData({
                headImg: headImg
              });
            }
          })
        } else if (index == 1) {
          wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['camera'],
            success(res) {
              console.log(res)
              // tempFilePath可以作为img标签的src属性显示图片

              var headImg = that.data.headImg;

              const tempFilePaths = res.tempFilePaths;

              var obj = {}
              obj.style = 1
              obj.url = tempFilePaths[0]

              headImg.push(obj)
              that.setData({
                headImg: headImg
              });
            }
          })
        }

      },
      fail(res) {
        console.log(res.errMsg)
      }
    })

  },
  // 选视频
  uploadvideo: function () {
    this.closetc()

    var uqid = this.data.uqid;
    console.log(uqid)
    var that = this
    wx.showActionSheet({
      itemList: ['从相册选取', '拍照'],
      success(res) {
        console.log(res.tapIndex)
        var index = res.tapIndex;

        var headImg = that.data.headImg;
        if (index == 0) {

          let num = 9; //一次最大上传九张

          if (headImg.length > 0) {
            num = 9 - headImg.length;
          }

          wx.chooseVideo({
            // count: num,
            maxDuration: 15,
            camera: 'back',

            sourceType: ['album'],
            success(res) {
              console.log(res)
              // tempFilePath可以作为img标签的src属性显示图片
              const tempFilePaths = res.tempFilePath;
              var obj = {}
              obj.style = 2
              obj.url = tempFilePaths
              headImg.push(obj)
              that.setData({
                headImg: headImg
              });
            }
          })
        } else if (index == 1) {
          wx.chooseVideo({

            maxDuration: 15,
            camera: 'back',

            sourceType: ['camera'],
            success(res) {
              console.log(res)
              // tempFilePath可以作为img标签的src属性显示图片

              var headImg = that.data.headImg;

              const tempFilePaths = res.tempFilePath;

              var obj = {}
              obj.style = 2
              obj.url = tempFilePaths
              headImg.push(obj)

              that.setData({
                headImg: headImg
              });
            }
          })
        }

      },
      fail(res) {
        console.log(res.errMsg)
      }
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})